<template>
  <div class="app-container layout-product-list">
    <div class="operate-container">
      <el-button type="primary" @click="handleCreateProduct()" size="small" v-if="isAdmin">新 建</el-button>
    </div>
    <div class="table-container">
      <el-table :data="list" v-loading="listLoading" class="product-table">
        <el-table-column label="产品名称" width="200">
          <template slot-scope="scope">{{scope.row.productName}}</template>
        </el-table-column>
        <el-table-column label="产品图片" width="160">
          <template slot-scope="scope">
            <el-image v-if="scope.row.fileId" style="width: 100px; height: 100px" :src="getFileUrl(scope.row.fileId)" fit="fill"></el-image>
            <div v-else class="no-img">暂无图片</div>
          </template>
        </el-table-column>
        <el-table-column label="产品属性" width="160">
          <template slot-scope="scope">
            <div
              v-for="(item,index) in scope.row.productSpecList || []"
              :key="index"
              class="text"
            >{{ item.specName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="产品品牌" width="200">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.brand" :key="index" class="text">{{ item }}</div>
          </template>
        </el-table-column>
        <el-table-column label="创建日期" width="200">
          <template slot-scope="scope">{{scope.row.createDate}}</template>
        </el-table-column>
        <el-table-column label="创建人" width="200">
          <template slot-scope="scope">{{scope.row.creator}}</template>
        </el-table-column>
        <el-table-column v-if="isAdmin" label="合伙人" width="200">
          <template slot-scope="scope">
            <div v-if="scope.row.username == null">
              无
            </div>
            <div v-else>
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-dropdown trigger="click" @command="clickMenu">
              <el-button type="infor" size="mini"  v-if="isAdmin">
                设置合伙人<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown" v-if="isAdmin">
                <el-dropdown-item :command="{partnerId:productor.userId, id: scope.row.id}" v-for="(productor, index) in productorList" :key="index">{{ productor.username }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
             <el-button size="mini" @click="handleDelete(scope.row)"  v-if="isAdmin">
                删除
              </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="listQuery.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="listQuery.pageNum"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>
<script>
import {getProductListByUserId, updatePartnerId,deleteProduct} from "@/api/product";
import {getUserById, getUserByRoleCode} from "@/api/login";
import {downloadFile} from "@/api/file";
import {mapGetters} from "vuex"
import Vue from "vue";

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10
};

export default {
  name: "ProductList",
  data() {
    return {
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: true,
      productorList: null
    };
  },
  created() {
   // this.downloadUrl = getDownloadUrl()
    this.getList();
    this.getAllProductor()
  },
  computed: {
    ...mapGetters(["roles"]),
    isAdmin() {
      console.log(this.roles)
      for(let i = 0; i < this.roles.length; i++) {
        if (this.roles[i].role_code == 'admin') {
          return true;
        }
      }
      return false;
    }
  },
  watch: {},
  methods: {
    async getList() {
      this.listLoading = true;
      await getProductListByUserId(this.listQuery).then(res => {
        if (res.code === 200) {
          this.listLoading = false;
          this.list = res.data.list;
          this.total = res.data.total;
        }
      });
      for (let i = 0; i < this.list.length; i++) {
        if (this.list[i].partnerId != null && this.list[i].partnerId != '') {
          getUserById(this.list[i].partnerId).then(res=>{
            Vue.set(this.list[i],"username",res.data.username)
          });
        }
      }
    },
    getFileUrl(fileId){
      return downloadFile(fileId);
    },
    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },
    handleCreateProduct() {
      this.$router.push({
        path:'/pms/createProduct'
      })
    },
    handleAfterCreate(result) {
      this.dialogOption.dialogVisible = false;
      if (result) {
        this.getList();
      }
    },
    handleEdit(row) {
      // 数据设置到缓存
      sessionStorage.setItem(`product-detail-${row.productCode}`, JSON.stringify(row))
        this.$router.push({
        path:'/pms/editProduct',query: {code: row.productCode}
      })
    },

       handleDelete(row) {
           this.$confirm('是否确定删除，一旦删除数据无法恢复', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteProduct(row.productCode).then(response => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList();
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          });
          
        
      })
    },
    getAllProductor() {
      if(this.isAdmin){
getUserByRoleCode('productor').then(res => this.productorList = res.data)
      }
      
    },
    async clickMenu(data) {
      let id = data.id;
      let partnerId = data.partnerId;
      await updatePartnerId(id, partnerId)
      for(let i = 0; i < this.list.length; i++) {
        if (this.list[i].id == id) {
          getUserById(partnerId).then(res=>this.$set(this.list[i],"username",res.data.username))
          break;
        }
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.layout-product-list {
  .product-table.el-table /deep/ td {
    padding: 4px 0px;
    .cell {
      line-height: 1
    }
  }
  .text {
    padding: 4px 0px;
  }
  .no-img {
    height: 100px;
    width: 100px;
    line-height: 100px;
  }
}
.form-dialog /deep/ .el-dialog__body {
  padding: 18px;
}
</style>
